/**
 *@描述：创建或编辑知识页面中的左侧功能列表
 *@作者：殷健
 *@创建时间：2022/7/7
 *@最后修改时间：2022/7/7
 */


import {useEffect, useRef, useState} from 'react';
import { useUpdateEffect } from 'ahooks';
import {Button, Collapse, Space, Menu, Dropdown, Modal,Popconfirm} from 'antd';
import type { MenuProps } from 'antd';
import ProForm, {
    ProFormItem,
    ProFormText,
} from '@ant-design/pro-form';

import {
    CloseOutlined,
    PlusOutlined,
    DeploymentUnitOutlined,
    FileDoneOutlined,
    LinkOutlined, UserOutlined, SaveOutlined,
} from '@ant-design/icons';

import classNames from 'classnames';

import styles from './section.less';
import {ProFormInstance} from "@ant-design/pro-components";
import {
     DelChapterRequest,
    getChapterTypesData, knowledgeChapterTemplateRequest, knowledgeChapterToKidRequest,
} from "@/pages/Dashboard/Knowledge/service";
import {useParams} from "umi";
import {uniqueId} from "lodash";
const { Panel } = Collapse;

const KnowledgeSection = ({
    knowledgeId,
    knowledgeType,
    value,
    onChange,
    structure,
    setStructure,
}: {
    knowledgeId?:string;
    knowledgeType?:string;
    value: AircasKB.Knowledge.SectionItem;
    onChange?: (val: AircasKB.Knowledge.SectionItem) => void;
    structure:AircasKB.Knowledge.SectionItem[];
    setStructure?: (val: AircasKB.Knowledge.SectionItem[]) => void;
}) => {

    //todo: 获取浏览器地址栏参数，此处获取的是知识类型
    const {
        type,
    }: {
        type: string;
    } = useParams();


    //todo: 设置组件状态
    const [curSection, setCurSection] = useState<AircasKB.Knowledge.SectionItem>(value);
    const [showUserSelectorModal, setShowUserSelectorModal] = useState<boolean>(false);
    const [structureType, SetStructureType] = useState("");
    const [ chapterTypes,setChapterTypes ] = useState<AircasKB.Knowledge.ChapterTypesResponse[]>([]);
    const [ chapterNo,setChapterNo ] = useState("0")


    useEffect(()=>{
        getChapterTypes();
    },[]);

    //组件初始化函数
    //todo: useEffect
    useEffect(()=>{
        if(knowledgeId){
            getKnowledgeChapterToKid(knowledgeId);
        }
        else{
            getKnowledgeChapterTemplate();
        }
    },[knowledgeId])

    //todo: useUpdateEffect
    useUpdateEffect(() => {
        onChange?.(curSection);
    }, [curSection]);

    //根据知识id查询章节列表，调用knowledgeChapterToKidRequest接口
    //todo: getKnowledgeChapterToKid
    const getKnowledgeChapterToKid = (id:string) => {
        knowledgeChapterToKidRequest({
            knowledgeId:id
        }).then((res:AircasKB.ResponseType<AircasKB.Knowledge.KnowledgeChapterToKidResponse[]>)=>{
            if(res.code == 200){
                const result:AircasKB.Knowledge.SectionItem[] = [];
                let chapterNos:number[] = [];
                res.data.map((item)=>{
                    result.push({
                        id:item.id,
                        title:item.title,
                        type:item.type,
                        chapterNo:item.chapterNo,
                    })
                    chapterNos.push(Number(item.chapterNo));
                })
                const chapterNoMax = Math.max(...chapterNos);
                // @ts-ignore
                setChapterNo(chapterNoMax);
                // console.log(chapterNoMax,'编号最大值');
                setStructure?.(result);
            }
        });
    }

    //根据知识类型，获取默认的知识结构列表，调用了knowledgeChapterTemplateRequest接口
    //todo: getKnowledgeChapterTemplate
    const getKnowledgeChapterTemplate = () => {
        knowledgeChapterTemplateRequest(
            {
                knowledgeType:type
            }
        ).then((res:AircasKB.ResponseType<AircasKB.Knowledge.KnowledgeChapterTemplateResponse[]>)=>{
            if(res.data && res.code == 200){
                const result:AircasKB.Knowledge.SectionItem[] = [];
                let chapterNos:number[] = [];
                if(res.data.length>0){
                    res.data.map((item)=>{
                        result.push({
                            chapterNo:item.chapterNo,
                            title:item.title,
                            type:item.type
                        })
                        chapterNos.push(Number(item.chapterNo));
                    })

                    const chapterNoMax = Math.max(...chapterNos);
                    // @ts-ignore
                    setChapterNo(chapterNoMax);
                    setStructure?.(result);
                }
            }
        })

    }


    //添加章节成功是触发的函数
    //todo: onSuccess
    const onSuccess = async (title:string) => {
        // if(knowledgeId){
            const result:AircasKB.Knowledge.SectionItem = {
                // id:Number(chapterNo)+1+"",
                title:title,
                type:structureType,
                chapterNo:Number(chapterNo)+1+""
            }

            //更新章节列表
            setStructure?.([...structure,result]);
            //更新章节最大编号
            setChapterNo(Number(chapterNo)+1+"");
            //设置选中的章节为当前添加的章节
            setCurSection(result);
            setShowUserSelectorModal(false);
        // }
        // else{
        //     // message.warn("请首先进入基本信息页面，填写基本信息！");
        //     // setCurSection({
        //     //     id: 'basic',
        //     //     title: '基本信息'
        //     // })
        //     setShowUserSelectorModal(false);
        // }

    }

    //获取章节类型，章节类型目前包括文章、代码、流程图
    //todo: getChapterTypes
    const getChapterTypes = async () => {
      const res:AircasKB.ResponseType<AircasKB.Knowledge.ChapterTypesResponse[]> = await getChapterTypesData();
      if(res.code == 200){
          setChapterTypes(res.data);
      }
    }

    //通过ID移除章节，在保存章节后使用
    //todo: DelSectionItemToId
    const DelSectionItemToId = (obj:AircasKB.Knowledge.SectionItem) => {
        let flag = 0;
        for(let i=0;i<structure.length;i++){
            if(structure[i].id == obj.id){
                structure.splice(i,1);
                flag = i;
                break;
            }
        }
        const result:AircasKB.Knowledge.SectionItem[] = [];
        structure.map((item)=>{
            // @ts-ignore
            result.push({
                title:item.title,
                type:item.type,
                chapterNo:item.chapterNo,
                id:item.id
            })
        })
        setStructure?.(result);
        const item:AircasKB.Knowledge.SectionItem = structure[flag-1];
        if(item){
            onChange?.(item);
            // @ts-ignore
            setChapterNo(item.chapterNo);
        }
        else{
            onChange?.({
                id: 'intellectualProperty',
                title: '知识产权',
            });
            setChapterNo("0");
        }
    }

    //通过标题移除章节，在没有保存章节使用
    //todo: DelSectionItemToId
    const DelSectionItemToTitle = (obj:AircasKB.Knowledge.SectionItem) => {
        let flag:number=0;
        for(let i=0;i<structure.length;i++){
            if(structure[i].title == obj.title){
                structure.splice(i,1);
                flag = i;
                break;
            }
        }
        const result:AircasKB.Knowledge.SectionItem[] = [];
        structure.map((item)=>{
            // @ts-ignore
            result.push({
                title:item.title,
                type:item.type,
                chapterNo:item.chapterNo,
                id:item.id,
            })
        })
        setStructure?.(result);
        const item:AircasKB.Knowledge.SectionItem = structure[flag-1];
        if(item){
            onChange?.(item);
        }
        else{
            onChange?.({
                id: 'intellectualProperty',
                title: '知识产权',
            });
        }

    }

    //删除章节，调用DelChapterRequest接口
    //todo: delChapter
    const delChapter = async (item:AircasKB.Knowledge.SectionItem) => {
        if(item.id){
            const res:AircasKB.ResponseType<AircasKB.Knowledge.DelChapterResponse> = await DelChapterRequest({
                knowledgeChapterId:item.id
            });
            if(res.code == 200){
                DelSectionItemToId(item);
            }
        }
        else{
            DelSectionItemToTitle(item);
        }
    }

    //点击下拉选择章节类型时触发，用于设置章节类型
    //todo: onClick
    const onClick: MenuProps['onClick'] = ({ key }) => {
        SetStructureType(key);
        setShowUserSelectorModal(true);
    };

    //创建章节类型下拉组件
    //todo: CreateMenu
    const CreateMenu = ()=>{
        // @ts-ignore
        return <Menu
            onClick={onClick}
            // @ts-ignore
            items={chapterTypes && chapterTypes.map((item)=>{
                let disabled:boolean = false;
                if(item.id == "25" || item.id == "26"){
                    return ({
                        key:item.id,
                        label:item.label,
                        disabled:disabled
                    })
                    // disabled = false;
                }
                // else{
                //     disabled = true;
                // }
                // return ({
                //     key:item.id,
                //     label:item.label,
                //     disabled:disabled
                // })

            })}
        />
    } ;


    return (
        <div>
        <Collapse
            defaultActiveKey={['1', '2', '3']}
            ghost
            expandIconPosition="end"
            className={styles.sectionWrapper}
        >
            <Panel header="知识概览" key="1" className={styles.content}>
                <div
                    className={classNames(styles.item, {
                        [styles.active]: value.id === 'basic',
                    })}
                    onClick={() =>
                        setCurSection({
                            id: 'basic',
                            title: '基本信息',
                        })
                    }
                >
                    🖌 &nbsp;&nbsp;基本信息
                </div>
                <div
                    className={classNames(styles.item, {
                        [styles.active]: value.id === 'intellectualProperty',
                    })}
                    onClick={() =>
                        setCurSection({
                            id: 'intellectualProperty',
                            title: '知识产权',
                        })
                    }
                >
                    👋 &nbsp;&nbsp;知识产权
                </div>
            </Panel>
            <Panel header="知识结构" key="2" className={styles.content}>
                {structure?.map((item: any) => {
                    return (
                        <div
                            key={uniqueId()}
                            className={classNames(styles.item, {
                                [styles.active]: value.chapterNo === item.chapterNo,
                            })}
                            onClick={() => setCurSection(item)}
                        >
                            {item.title}
                            <Popconfirm
                                title="您确定要删除该章节吗？"
                                onConfirm={()=>{
                                    delChapter(item)
                                }}
                                okText="是"
                                cancelText="否"
                            >
                            <Button
                                type="link"
                                size="small"
                                danger
                                icon={<CloseOutlined />}
                                className={styles.removeBtn}
                            ></Button>
                            </Popconfirm>
                        </div>
                    );
                })}
                <Dropdown overlay={CreateMenu}>
                    <Button type="link" size="small" icon={<PlusOutlined />} className={styles.addBtn} onClick={e => e.preventDefault()}>
                        增加章节
                    </Button>
                </Dropdown>

            </Panel>
            <Panel header="附加内容" key="3" className={styles.content}>
                <div
                    className={classNames(styles.item, {
                        [styles.active]: value.id === 'attachment',
                    })}
                    onClick={() => setCurSection({ id: 'attachment', title: '附件管理' })}
                >
                    <Space>
                        <FileDoneOutlined />
                        附件管理
                    </Space>
                </div>
                <div
                    className={classNames(styles.item, {
                        [styles.active]: value.id === 'relevance',
                    })}
                    onClick={() => setCurSection({ id: 'relevance', title: '知识关联' })}
                >
                    <Space>
                        <DeploymentUnitOutlined />
                        知识关联
                    </Space>
                </div>
                <div
                    className={classNames(styles.item, {
                        [styles.active]: value.id === 'quote',
                    })}
                    onClick={() => setCurSection({ id: 'quote', title: '参考引用' })}
                >
                    <Space>
                        <LinkOutlined />
                        参考引用
                    </Space>
                </div>
            </Panel>
        </Collapse>

            {showUserSelectorModal && (
                <StructureModal
                    onSuccess={onSuccess}
                    show={showUserSelectorModal}
                    onCancel={() => setShowUserSelectorModal(false)}
                ></StructureModal>
            )}


            {/*<Button*/}
            {/*    size="large"*/}
            {/*    type="primary"*/}
            {/*    htmlType="submit"*/}
            {/*    icon={<SaveOutlined />}*/}
            {/*    style={{ marginLeft: 80 }}*/}
            {/*>*/}
            {/*    保存*/}
            {/*</Button>*/}

        </div>


    );
};


const StructureModal = ({
                            show,
                            onCancel,
                            onSuccess,
                           }: {
    show: boolean;
    onCancel?: () => void;
    onSuccess?:(title:string)=>void;
}) => {
    const formRef = useRef<ProFormInstance>();
    const doSave = async (values:FormData) => {
        const title:string = values['title'].toString();
        // @ts-ignore
        onSuccess(title);
    }

    return (
        <Modal
            title={
                <Space>
                    <UserOutlined />
                    添加章节
                </Space>
            }
            visible={show}
            centered
            destroyOnClose={true}
            footer={false}
            bodyStyle={{ padding: 10 }}
            onCancel={onCancel}
        >

            <ProForm
                formRef={formRef}
                layout="horizontal"
                className={styles.form}
                onFinish={doSave}
                labelCol={{
                    style: {
                        width: 80,
                    },
                }}
                submitter={false}
            >
                <ProFormText
                    name="title"
                    label="章节名称"
                    required
                    rules={[
                        {
                            required: true,
                            message: '请输入片段名称',
                        },
                    ]}
                ></ProFormText>
                <ProFormItem>
                    <Button
                        size="large"
                        type="primary"
                        htmlType="submit"
                        icon={<SaveOutlined />}
                        style={{ marginLeft: 80 }}
                    >
                        确定
                    </Button>
                    </ProFormItem>
            </ProForm>

        </Modal>
    );
};
export { StructureModal };
export default KnowledgeSection;
